package com.netty.common;

import com.alibaba.fastjson.JSONObject;
import com.netty.module.ChatMessage;

import java.nio.ByteBuffer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
	private final ChannelGroup group;
	
	public TextWebSocketFrameHandler(ChannelGroup group) {
		this.group = group;
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
			ctx.pipeline().remove(HttpRequestHandler.class);
			Channel channel = ctx.channel();
			group.add(channel);

			System.out.println("group长度："+group.size());

			//加入当前, 上线人员推送前端 多人聊天室 用户列表中去，
			/*ChatMessage message = new ChatMessage(null, "");
			group.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message,SerializerFeature.DisableCircularReferenceDetect)));*/

		}else {
			super.userEventTriggered(ctx, evt);
		}
	}

	/**
	 * 发送消息时走该方法
	 * @param ctx
	 * @param msg
	 * @throws Exception
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		Channel channel = ctx.channel();
		String from = channel.attr(ChatConstants.CHANNEL_TOKEN_KEY).get();
		if(from == null) {
			group.writeAndFlush("OK");
		}else {
			String msgText = msg.text();
			JSONObject json = JSONObject.parseObject(msgText);
			String to = json.getString("curPatientId");
			String t = json.getString("text");
			ChatMessage message = new ChatMessage(from, t,to);
			String text = JSON.toJSONString(message,SerializerFeature.DisableCircularReferenceDetect);
			//群发
			//group.writeAndFlush(new TextWebSocketFrame(text));

			//一对一发送
			Channel receiver = ChatConstants.channels.get(message.getTo());
			if(receiver!=null) {
				ByteBuffer bb = ByteBuffer.allocate(32);
				
//				receiver.writeAndFlush(bb);
				TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(text);
				receiver.writeAndFlush(textWebSocketFrame);
			}
		}
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		//"Current channel channelInactive";
		offlines(ctx);
	}
	
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		//"Current channel handlerRemoved";
		offlines(ctx);
	}
	
	private void offlines(ChannelHandlerContext ctx) {
		Channel channel = ctx.channel();
		String token = channel.attr(ChatConstants.CHANNEL_TOKEN_KEY).get();
		ChatConstants.removeOnlines(token);
		group.remove(channel);
		ctx.close();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		offlines(ctx);
	}
}
